package com.fanshuai.jmx.agent;

import com.fanshuai.jmx.mbean.Hello;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import java.lang.management.ManagementFactory;
import java.rmi.registry.LocateRegistry;

public class RMIAgent {
    public static void init() throws Exception {
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        ObjectName objectName = new ObjectName("custom:name=hello");
        Hello hello = new Hello();
        hello.setName("林芳伊");
        hello.setAge(18);

        mBeanServer.registerMBean(hello, objectName);

        LocateRegistry.createRegistry(1999);
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1999/jmxrmi");
        JMXConnectorServer jmxConnectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mBeanServer);
        jmxConnectorServer.start();
    }
}
